<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <searchBar :show-channel-id="false" :show-server-id="false" @transferFilter="handleFilter" />
      <el-button v-if="checkPermission(permissionRoles.iospackage_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加提审包</el-button>
    </div>

    <el-table v-loading="listLoading" :data="list" border height="725">
      <el-table-column fixed prop="name" align="center" label="包名"></el-table-column>
      <el-table-column prop="version" align="center" label="版号"></el-table-column>
      <el-table-column prop="remark" align="center" label="备注"></el-table-column>
      <el-table-column prop="sname" align="center" label="审核服"></el-table-column>
      <el-table-column align="center" label="审核状态">
        <template slot-scope="{row}">
          <el-tag v-if="row.status === 0" type="danger">待审核</el-tag>
          <el-tag v-else type="success">已过审</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-if="checkPermission(permissionRoles.iospackage_edit)" type="text" size="small" @click="handleEdit(scope)">修改</el-button>
          <el-button v-if="checkPermission(permissionRoles.iospackage_del)" type="text" size="small" title="删除" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="80px" label-position="left">
        <el-form-item label="包名" prop="name">
          <el-input v-model="dataForm.name" class="defaut-input" placeholder="填写IOS包名" />
        </el-form-item>
        <el-form-item label="版号" prop="version">
          <el-input v-model="dataForm.version" class="defaut-input" placeholder="填写版号" />
        </el-form-item>
        <el-form-item label="审核服" prop="sid">
          <el-select v-model="dataForm.sid" class="defaut-input" filterable clearable>
            <el-option
              v-for="item in serverList"
              :key="item.id"
              :label="item.name+'('+item.sid+')'"
              :value="item.sid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="dataForm.remark" class="defaut-input" placeholder="填写备注" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-radio-group v-model="dataForm.status">
            <el-radio :label="0">待审核</el-radio>
            <el-radio :label="1">已过审</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { objectMerge, deepClone } from '@/utils'
import { getIosPackageList, handleIosPackage, deleteIosPackage, getServerList } from '@/api/ops'
import Pagination from '@/components/Pagination'
import SearchBar from '@/components/SearchBar'

const defaultItem = {
  id: '',
  name: '',
  version: '',
  sid: '',
  remark: '',
  status: 0
}
export default {
  name: 'ChannelPackage',
  components: { SearchBar, Pagination },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      total: 0,
      listQuery: {
        page: 1,
        limit: 100
      },
      searchBarQuery: {},
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      rules: {
        name: [{ required: true, message: '请填写包名', trigger: 'blur' }],
        version: [{ required: true, message: '请填写版本号', trigger: 'blur' }],
        sid: [{ required: true, message: '请选择审核服', trigger: 'blur' }]
      },
      list: [],
      serverList: [],
      dialogVisible: false,
      dialogType: 'new',
      textMap: {
        edit: '编辑',
        new: '新增'
      }
    }
  },
  created() {
    this.init()
    this.getServerList()
  },
  methods: {
    checkPermission,
    init() {
      this.getList()
    },
    async getServerList() {
      const res = await getServerList()
      for (let i = 0; i < res.data.items.length; i++) {
        if (res.data.items[i].sid <= 1000) {
          this.serverList.push(res.data.items[i])
        }
      }
    },
    handleFilter(query) {
      this.searchBarQuery = query
      this.getList()
    },
    async getList() {
      const query = objectMerge(this.searchBarQuery, this.listQuery)
      this.listLoading = true
      const res = await getIosPackageList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(scope.row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete({ $index, row }) {
      this.$confirm('你确定要删除此列吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteIosPackage(row.id)
          this.list.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === 'edit'
          handleIosPackage(this.dataForm).then(response => {
            if (response.status) {
              if (isEdit) {
                for (let index = 0; index < this.list.length; index++) {
                  if (this.list[index].id === this.dataForm.id) {
                    this.list.splice(index, 1, Object.assign({}, this.dataForm))
                    break
                  }
                }
              } else {
                this.list.push(response.data)
              }
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}

.el-table td {
  text-align: left !important;
}
.el-table {
  font-size: 14px;
}
.el-table td, .el-table th {
  padding: 10px 0;
}
.el-table th>.cell {
  padding-left: 10px;
  padding-right: 10px;
}
</style>
